package com.channel.temperature.collect.ui.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.lifecycle.lifecycleScope
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.android.material.tabs.TabLayoutMediator
import com.hjq.toast.ToastUtils
import com.hjy.bluetooth.HBluetooth
import com.channel.temperature.collect.R
import com.channel.temperature.collect.app.api.NetUrl
import com.channel.temperature.collect.app.base.BaseActivity
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.MyWorker
import com.channel.temperature.collect.app.util.NetCheckUtils
import com.channel.temperature.collect.app.util.RSAUtils
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.data.response.ApiResponseTwo
import com.channel.temperature.collect.databinding.ActivityCollectHomeBinding
import com.channel.temperature.collect.ui.adapter.CollectHomeAdapter
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.base.BaseViewModel
import me.hgj.mvvmhelper.base.appContext
import me.hgj.mvvmhelper.ext.setOnclickNoRepeat
import me.hgj.mvvmhelper.ext.toStartActivity
import rxhttp.toAwait
import rxhttp.wrapper.param.RxHttp
import java.security.KeyFactory
import java.security.spec.X509EncodedKeySpec
import java.util.Base64
import java.util.concurrent.TimeUnit


class CollectHomeActivity : BaseActivity<BaseViewModel, ActivityCollectHomeBinding>(),
    LocationListener {
    private lateinit var locationManager: LocationManager

    companion object {
        val titles = arrayOf("计划任务", "数据采集", "数据处理", "系统设置")
        val selectedArr = arrayOf(
            R.mipmap.bottom_task_selected,
            R.mipmap.bottom_online_selected,
            R.mipmap.bottom_data_selected,
            R.mipmap.bottom_setting_selected
        )
        val unSelectedArr = arrayOf(
            R.mipmap.bottom_task,
            R.mipmap.bottom_online,
            R.mipmap.bottom_data,
            R.mipmap.bottom_setting
        )

        fun getTabView(context: Context, position: Int): View {
            val view: View = LayoutInflater.from(context).inflate(R.layout.icon_view, null)
            var text_tips = view.findViewById<TextView>(R.id.tabtext)
            var img = view.findViewById<ImageView>(R.id.tabicon)
            if (position == 0) {
                text_tips.text = titles[position]
                text_tips.setTextColor(context.resources.getColor(R.color.color_0271C0))
                img.setImageResource(selectedArr[position])
            } else {
                text_tips.text = titles[position]
                text_tips.setTextColor(context.resources.getColor(R.color.color_BFBFBF))
                img.setImageResource(unSelectedArr[position])
            }

            return view
        }

    }

    private var DEFAULT_POSITION = 0

    override fun initView(savedInstanceState: Bundle?) {
        //设置适配器
        mBind.mainViewPager.adapter = CollectHomeAdapter(this)
        //设置缓存页面数量
        mBind.mainViewPager.offscreenPageLimit = mBind.mainViewPager.adapter!!.itemCount
        //禁止滑动
        mBind.mainViewPager.isUserInputEnabled = false
        TabLayoutMediator(mBind.mainNavigation, mBind.mainViewPager, true, false) { tab, position ->
            tab.setCustomView(getTabView(this, position));
        }.attach()
        mBind.mainNavigation.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                var tabView = tab.customView
                tabView?.findViewById<ImageView>(R.id.tabicon)
                    ?.setImageResource(selectedArr[tab.position])
                tabView?.findViewById<TextView>(R.id.tabtext)
                    ?.setText(titles[tab.position])
                tabView?.findViewById<TextView>(R.id.tabtext)
                    ?.setTextColor(resources.getColor(R.color.color_0271C0))
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                var tabView = tab.customView
                tabView?.findViewById<ImageView>(R.id.tabicon)
                    ?.setImageResource(unSelectedArr[tab.position])
                tabView?.findViewById<TextView>(R.id.tabtext)
                    ?.setText(titles[tab.position])
                tabView?.findViewById<TextView>(R.id.tabtext)
                    ?.setTextColor(resources.getColor(R.color.color_BFBFBF))
            }

            override fun onTabReselected(tab: TabLayout.Tab) {

            }
        })

        val displayWidth = resources.displayMetrics.widthPixels
        // 设置每个标签的宽度权重相等
        for (i in 0 until mBind.mainNavigation.tabCount) {
            val params = mBind.mainNavigation.getTabAt(i)?.view?.layoutParams
            params?.width = displayWidth / mBind.mainNavigation.tabCount
            mBind.mainNavigation.getTabAt(i)?.view?.layoutParams = params
        }
        mBind.mainNavigation.getTabAt(0)?.select()


        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager

        // 检查权限并请求位置更新
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return
            }
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0f, this)
        } else {
            Toast.makeText(this, "GPS is disabled", Toast.LENGTH_LONG).show()
        }
        //发布后台任务
        val periodicWorkRequest = PeriodicWorkRequest.Builder(
            MyWorker::class.java,
            15,
            TimeUnit.MINUTES
        ).build()
        WorkManager.getInstance(appContext)
            .enqueueUniquePeriodicWork(
                "my_periodic_work",
                ExistingPeriodicWorkPolicy.KEEP,
                periodicWorkRequest
            )
        //上传日志
        uploadLog()
    }

    fun uploadLog() {
        if (NetCheckUtils.isNetworkAvailable()) {
            lifecycleScope.launch {
                var location = mmkv.getString(ValueKey.APP_LOCATION_KEY, "")
                // 执行任务逻辑
                var encodeString = RSAUtils.encryptByPublicKey(
                    getAndroidId(), KeyFactory.getInstance("RSA").generatePublic(
                        X509EncodedKeySpec(
                            Base64.getDecoder().decode(RSAUtils.publicKeyString)
                        )
                    )
                )
                var dataBean = RxHttp.get(NetUrl.BASE_URL + "/index/appdevices/add_log")
                    .add("mData", encodeString)
                    .add("longx", if (location.isNullOrEmpty()) "" else location.split("_")[0])
                    .add("lat", if (location.isNullOrEmpty()) "" else location.split("_")[1])
                    .toAwait<ApiResponseTwo<Any>>()
                    .await()
                Log.e("测试", "测试 " + dataBean.toString())
            }
        }


    }

    private fun getAndroidId(): String {
        var uniqueID = Settings.Secure.getString(
            appContext.contentResolver, Settings.Secure.ANDROID_ID
        )
        return uniqueID
    }

    override fun onBindViewClick() {
        //绑定点击事件
        setOnclickNoRepeat(
            mToolbar.getRightId(),
        ) {
            when (it) {
                mToolbar.getRightId() -> {
                    toStartActivity(SystemSettingActivity::class.java)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        locationManager.removeUpdates(this)
        Log.e("测试", "测试 主页销毁")
        WorkManager.getInstance(application).cancelAllWork()
    }

    override fun onResume() {
        super.onResume()
        if (HBluetooth.getInstance().isReceiverNull) {
            //解决APP在使用中崩溃后蓝牙扫描服务变成null扫描不到设备的bug
            HBluetooth.getInstance().enableBluetooth()
        } else {
            Log.e("onResume", "蓝牙服务正常")
        }
    }

    override fun showToolBar() = false
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (getSupportFragmentManager().getFragments().size > 0) {
            var fragments = getSupportFragmentManager().getFragments();
            for (i in 0 until fragments.size) {
                fragments[i].onActivityResult(requestCode, resultCode, data);
            }

        }
    }

    private var mExitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mExitTime > 2000) {
                var mHelperUtils: Any
                ToastUtils.show("再按一次退出程序")
                mExitTime = System.currentTimeMillis()
            } else {
                HBluetooth.getInstance().release()
                CollectHomeActivity@ this.finish()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
    }

    override fun onLocationChanged(location: Location) {
        Log.e("测试", "坐标" + location.longitude + "    " + location.latitude)
        mmkv.putString(ValueKey.APP_LOCATION_KEY, "" + location.longitude + "_" + location.latitude)
    }


}